<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="编码值" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入编码值"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:qr:add']"
        >生成小程序码</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:qr:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:qr:export']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="qrList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="编码值" align="center" prop="code" />
      <el-table-column label="图片" align="center">
        <template v-slot="scope">
          <el-image :src="scope.row.imageUrl"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="扫码次数" align="center" prop="count" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-plus"
            size="mini"
            @click="showGoodsDialog(scope.row)"
            v-hasPermi="['system:qr:add']"
          >编辑商品</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:qr:remove']"
          >删除小程序码</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!--对小程序增加商品的对话框-->
    <el-dialog
      title="编辑商品"
      :visible.sync="qrGoodsVisible"
      width="51%">
      <el-transfer
        style="text-align: left; display: inline-block"
        target-order="unshift"
        v-model="TargetValue"
        filterable
        :render-content="renderFunc"
        :titles="['所有商品', '当前奖池']"
        :button-texts="['撤回', '添加']"
        @change="changeTargetValue"
        :format="{
        noChecked: '${total}',
        hasChecked: '${checked}/${total}'
      }"
        :data="sourceValue">
      </el-transfer>
      <span slot="footer" class="dialog-footer">
    <el-button @click="qrGoodsVisible = false">取 消</el-button>
    <el-button type="primary" @click="addGoods4Qr" :disabled="!cannotSubmit">确 定</el-button>
  </span>
    </el-dialog>

    <!-- 生成小程序码的对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入编码值" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listQr, getQr, delQr, addQr, updateQr4Goods, exportQr } from "@/api/wx/qr";
import {getGoodsNotInQr,getGoodsInQr} from "@/api/wx/goods";

export default {
  name: "Qr",
  data() {
    const validateCode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入编码值'));
      } else {
        const regex = /[0-9a-zA-Z-_#]{1,255}/;
        if (regex.test(value)) {
          callback();
        }else{
          this.$message.error("请输入[0-9、a-z、A-Z、-、_、#]")
        }
      }
    };
    return {
      // 控制增加商品的对话框是否可见
      qrGoodsVisible:false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【小程序码】表格数据
      qrList: [],
      // 弹出层标题
      title: "",
      // 目标数组，也就是存放小程序码对应的商品的id的那个数组
      TargetValue:[],
      // 将请求得到的目标数组的数据源保存下来，这边是一个副本，用于后面与TargetValue比较差异
      originTargetValue:[],
      // 源数组，存放当前小程序码没有对应的商品
      sourceValue:[],
      // 定义一个标志符，用于判断提交按钮是否可以点击
      // 自定义数据项渲染函数
      renderFunc(h, option) {
        return <span>{option.key }- {option.label}</span>;
      },
      cannotSubmit:false,
      qrId:"",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        code: null,
        imageUrl: null,
        count: null
      },
      // 表单参数
      form: {
        code:""
      },
      // 表单校验
      rules: {
        code: [
          { required: true, message: '请输入编码值', trigger: 'blur' },
          { validator: validateCode, trigger: 'blur'}
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询【小程序码】列表 */
    getList() {
      this.loading = true;
      listQr(this.queryParams).then(response => {
        this.qrList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        levelOneId: null,
        levelOneContent: null,
        detailContent: null,
        count: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "生成小程序码";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getQr(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改【请填写功能名称】";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["formRef"].validate(valid => {
        if (valid) {
          addQr(this.form.code).then(response => {
            if (response.code === 200) {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$confirm('是否确认删除小程序码编号为"' + id + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delQr(id);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有【请填写功能名称】数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportQr(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
    /** 弹出添加商品到小程序码的对话框 */
    showGoodsDialog(row) {
      this.qrId = row.id;
      let tempValue = []
      getGoodsNotInQr(row.id).then(res=>{
        tempValue = res.data.map(e=>{
          return {"key":e.id,"label":e.name};
        });
        getGoodsInQr(row.id).then(res=>{
          this.TargetValue = res.data.map(e=>{
            return e.id;
          });
          const arr = res.data.map(e=>{
            return {"key":e.id,"label":e.name};
          })
          this.sourceValue = [...tempValue,...arr];
          this.originTargetValue = this.TargetValue;
        });
      });

      this.qrGoodsVisible = true;
    },
    // 找寻新增的差异
    showAddArray() {
      const addArr = [];// 当前该小程序码新增了哪些商品，揪出这些差异
      this.TargetValue.forEach(e=>{
        if(!this.originTargetValue.includes(e)) {
          // 如果原始数组（由id组成）不包含修改后的TargetValue的id，那 那些id就是新增的,push
          addArr.push(e);
        }
      });
      return addArr;
    },
    // 找寻删减的差异
    showDelArray() {
      const delArr = [];// 构建一个删除了哪些商品id的数组，揪出这些差异
      this.originTargetValue.forEach(e=>{
        if(!this.TargetValue.includes(e)) {
          // 反过来，如果TargetValue（由id组成）不包含修改后的originTargetValue的id，那 那些id就是删除的,push
          delArr.push(e)
        }
      });
      return delArr;
    },
    /** 向小程序码添加商品 */
    addGoods4Qr() {
      // 发送请求前的校验
      if( this.TargetValue.length <6) {
        this.$message.warning("至少添加6件商品来填充转盘");
        return;
      }
      // 比较原来数组和修改后的数组的差异，找出新增的商品id和删除的商品id
      // 这样就避免了将该小程序对应的商品id全部删除再全部插入的这种比较笨的更新操作
      const addArray = this.showAddArray();
      const delArray = this.showDelArray();
      const formData = new FormData();
      formData.append("addIds",addArray);
      formData.append("delIds",delArray);
      // 构建完成，发送请求
      updateQr4Goods(this.qrId,formData).then(()=>{
        this.$message.success("更新成功");
      }).catch(()=>{
        this.$message.error("更新失败")
      });
      this.qrGoodsVisible = false;
    },
    // 用于判断右侧列表的内容是否发生了更新，从而决定按钮是否可以点击提交
    changeTargetValue() {
      this.cannotSubmit = this.showAddArray().length !==0 || this.showDelArray().length !==0;
    }
  }
};
</script>
